package com.atsmart.app.activity;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;


import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.wwj.finger.media.CropImageView;
import com.wwj.finger.media.MonitoredActivity;
import com.wwj.finger.media.Util;
import com.wwj.finger.util.HighlightView;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ShowPicActivity extends MonitoredActivity {
	public boolean mSaving;
	LinearLayout layout;
	private CropImageView mImageView;
	private final Handler mHandler = new Handler();
	private boolean mCircleCrop = false;
	HighlightView mCrop;
	Bitmap mBitmap;
	private Context context;
	private Dialog dialog;
	private int screen_width, screen_height;
	/**
	 * Activity在创建的时候回调的函数 主要用来初始化一些变量
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showpic);
	
		context = this;
		dialog = DialogUtil.getLoadingDialog(context);
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		screen_height = metrics.heightPixels;
		screen_width = metrics.widthPixels;
		
		mImageView = (CropImageView) findViewById(R.id.image);
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
				Message msg = new Message();
				msg.what = 0x001;
				handler.sendMessage(msg);
				try{
					File file = new File(PrefsUtils.getImg());
					if (file.exists()) {
						mBitmap = BitmapFactory.decodeFile(PrefsUtils.getImg());
					}
//					String filename = "320431" + ".jpg";
//					String directory = BizApp.getInstance().getFilePath()+"/"+"tems"+"/";
//					String filepath = directory + "/" + filename;
//					mBitmap = BitmapFactory.decodeFile(filepath);
					 
					Log.e("TAG", "bitmap.getWidth: = " + mBitmap.getWidth() + " , mBitmap.getHeight: = " + mBitmap.getHeight());
					if(mBitmap != null){
						if(mBitmap.getWidth() > mBitmap.getHeight()){
							Matrix matrix = new Matrix();
							matrix.setRotate(90);
							PrefsUtils.setHaseRote("1");
							mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
						}else{
							PrefsUtils.setHaseRote(null);
						}
					}else{
						Toast.makeText(context, "获取图片失败", Toast.LENGTH_SHORT).show();
					}
				}catch (Exception e) {
					finish();
				}
				return null;
			}
			
			protected void onPostExecute(Void result) {
				if(mBitmap != null){
//					try{
//						if(mBitmap.getWidth() < screen_width && mBitmap.getHeight() < screen_height){
//							Matrix matr = new Matrix();
//							float scaleWidth = (float) screen_width/mBitmap.getWidth();
//							float scaleHeight = (float) screen_height / mBitmap.getHeight();
//							matr.postScale(scaleWidth, scaleHeight);
//							mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),mBitmap.getHeight(), matr, true);
//						}
//					}catch (Exception e) {
//					}
					startFaceDetection();
				}else{
					finish();
				}
				Message msg = new Message();
				msg.what = 0x002;
				handler.sendMessage(msg);
			};
		}.execute();
		
//		Log.e("TAG", "screen_width: = " + screen_width+";; screen_height: = " + screen_height);
		
		findViewById(R.id.discard).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View v) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});

		findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				onSaveClicked();
			}
		});
	}
	 
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x001){
				dialog.show();
			}else if(msg.what == 0x002){
				dialog.cancel();
			}else if(msg.what == 0x302){
				Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show();
			}
		};
	};

	private void startFaceDetection() {
		
//		Log.e("bitmap", mBitmap.getWidth() + " ;; " + mBitmap.getHeight());
//		Log.e("mImageView", mImageView.getMeasuredWidth() + " ;; " + mImageView.getMeasuredHeight());
		// 设置要剪切的image
		mImageView.setImageBitmapResetBase(mBitmap, true);
		
		Util.startBackgroundJob(this, null, "请稍候...", new Runnable() {
			public void run() {
				final CountDownLatch latch = new CountDownLatch(1);
				final Bitmap b = mBitmap;
				mHandler.post(new Runnable() {
					public void run() {
						if (b != mBitmap && b != null) {
							mImageView.setImageBitmapResetBase(b, true);
							mBitmap.recycle();
							mBitmap = b;
						}
						if (mImageView.getScale() == 1.0f) {
							mImageView.center(true, true);
						}
						latch.countDown();
					}
				});
				try {
					latch.await();
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
				mRunFaceDetection.run();
			}
		}, mHandler);
	}

	/**
	 * 保存按钮点击后，剪裁图片
	 */
	Bitmap croppedImage = null;
	private void onSaveClicked() {
		// CR: TODO!
		// TODO this code needs to change to use the decode/crop/encode single
		// step api so that we don't require that the whole (possibly large)
		// bitmap doesn't have to be read into memory
		if (mSaving)
			return;

		if (mCrop == null) {
			return;
		}

		mSaving = true;

		Rect r = mCrop.getCropRect();

		int width = r.width(); // CR: final == happy panda!
		int height = r.height();

		croppedImage = Bitmap.createBitmap(width, height,
				mCircleCrop ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
		{
			Canvas canvas = new Canvas(croppedImage);
			Rect dstRect = new Rect(0, 0, width, height);
			canvas.drawBitmap(mBitmap, r, dstRect, null);
		}

		if (mCircleCrop) {
			Canvas c = new Canvas(croppedImage);
			Path p = new Path();
			p.addCircle(width / 2F, height / 2F, width / 2F, Path.Direction.CW);
			c.clipPath(p, Region.Op.DIFFERENCE);
			c.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
		}

			
			new AsyncTask<Void, Void, Void>() {

				@Override
				protected Void doInBackground(Void... params) {
					Message msg = new Message();
					msg.what = 0x001;
					handler.sendMessage(msg);
//					Log.e("TAG", "保存： = "  + " width: = " + croppedImage.getWidth() + " ;; height: = " + croppedImage.getHeight());
//					SavePicInLocal(croppedImage);
					saveCamera(croppedImage, false);
					return null;
				}
				
				@Override
				protected void onPostExecute(Void result) {
					Message msg = new Message();
					msg.what = 0x002;
					handler.sendMessage(msg);
					Intent it = new Intent(); 
					it.setClass(ShowPicActivity.this, ReportActivity.class);
		            setResult(RESULT_OK, it); 
					finish();
					super.onPostExecute(result);
				}
			}.execute();
			
	}

	private String fileName;  
	// 保存拍摄的照片到手机的sd卡  
    private void SavePicInLocal(Bitmap bitmap) {  
        FileOutputStream fos = null;  
        BufferedOutputStream bos = null;  
        ByteArrayOutputStream baos = null; // 字节数组输出流  
        try {  
            baos = new ByteArrayOutputStream();  
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  
            byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组  
            String saveDir = BizApp.getInstance().getFilePath() + "/tem_img"; 
            File dir = new File(saveDir);  
            if (!dir.exists()) {  
                dir.mkdir(); // 创建文件夹  
            }  
            fileName = saveDir + "/" + System.currentTimeMillis() + ".PNG";  
            File file = new File(fileName);  
            file.delete();  
            if (!file.exists()) {  
                file.createNewFile();// 创建文件  
//                Log.e("PicDir", file.getPath());  
            }  
            if(!StringUtil.isEmptyOrNull(PrefsUtils.getImgs())){
            	PrefsUtils.setImgs(null);
            }
            PrefsUtils.setImgs(file.getPath());
//            Log.e(" showpicactivity 写入本地", "file: = " + PrefsUtils.getImgs());
            // 将字节数组写入到刚创建的图片文件中  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(byteArray);  
  
        } catch (Exception e) {  
//        	Log.e("showpicactivity", "保存图片异常");
        	Message msg = new Message();
        	msg.what = 0x302;
        	handler.sendMessage(msg);
            //e.printStackTrace();  
        } finally {  
            if (baos != null) {  
                try {  
                    baos.close();  
                } catch (Exception e) {  
                    //e.printStackTrace();  
                }  
            }  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (Exception e) {  
                    //e.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (Exception e) {  
                    //e.printStackTrace();  
                }  
            }  
  
            if(bitmap != null){
            	bitmap.recycle();
            	bitmap = null;
            }
            
            if(mBitmap != null){
            	mBitmap.recycle();
            	mBitmap = null;
            }
        }  
  
    }  
	
    Uri imgUri;
    private void saveCamera(Bitmap theBmp, boolean recycle) {
    	try{
			byte[] data = null;
			try {
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				theBmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
				data = bytes.toByteArray();
				bytes.close();
				if (recycle)
					theBmp.recycle();
			} catch (Exception e) {
				// Log.e("imag", "保存图片异常");
				if (theBmp != null) {
					theBmp.recycle();
				}
				//e.printStackTrace();
			}
			theBmp = null;
			// make URI to save image
			SimpleDateFormat timeStampFormat = new SimpleDateFormat(
					"yyyyMMddhh_mm_ss");
			String filename = timeStampFormat.format(new Date());
			filename = filename + ".jpg";
			ContentValues values = new ContentValues();
			values.put(Media.TITLE, filename);
			values.put(Media.DISPLAY_NAME, filename);
			values.put(Media.DESCRIPTION, "Image capture by camera");
			values.put(Media.MIME_TYPE, "image/jpeg");
	
			String directory =  BizApp.getInstance().getFilePath() + "/tem_img"; 
			String filepath = directory + "/" + filename;
			values.put("_data", filepath);
			// Log.e("iamgeURL", "befor imageUri");
			imgUri = getContentResolver()
					.insert(Media.EXTERNAL_CONTENT_URI, values);
			// Log.e("iamgeURL", "after imageUri");
	
			try {
				OutputStream filoutputStream = getContentResolver()
						.openOutputStream(imgUri);
				filoutputStream.write(data);
				filoutputStream.flush();
				filoutputStream.close();
	
			} catch (Exception ex) {
				// Log.e("iamgeURL", "imagURL is error");
				imgUri = null;
				Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
			}
			data = null;
			System.gc();
			if(!StringUtil.isEmptyOrNull(PrefsUtils.getImgs())){
	        	PrefsUtils.setImgs(null);
	        }
	        PrefsUtils.setImgs(filepath);
    	}catch (Exception e) {
    		Message msg = new Message();
        	msg.what = 0x302;
        	handler.sendMessage(msg);
    	}
	}
    
	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}
		return sdDir.toString();

	}

	Runnable mRunFaceDetection = new Runnable() {

		Matrix mImageMatrix;

		// Create a default HightlightView if we found no face in the picture.
		private void makeDefault() {
			HighlightView hv = new HighlightView(mImageView);

			int width = mBitmap.getWidth();
			int height = mBitmap.getHeight();
//			Log.e("TAG", "showPicActivity图片尺寸 width: = " + width + " , height: = " + height);
			Rect imageRect = new Rect(0, 0, width, height);
//			int x = screen_width/2 - 151;
//			int y = screen_height/2 - 151;
//			RectF cropRect = new RectF(x, y, x + 302, y + 302);
			
			int offset = screen_width/2-2;
			int x = screen_width/2 - offset;
			int y = screen_height/2 - offset;
			RectF cropRect = new RectF(x, y, x + 2*offset, y + 2*offset);
			hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop, false, screen_width, screen_height);
			mImageView.add(hv);
		}

		public void run() {
			mImageMatrix = mImageView.getImageMatrix();
			mHandler.post(new Runnable() {
				public void run() {
					makeDefault();
					mImageView.invalidate();
					if (mImageView.mHighlightViews.size() == 1) {
						mCrop = mImageView.mHighlightViews.get(0);
						mCrop.setFocus(true);
					}
				}
			});
		}
	};
}